const idate = require('./idate')
const crypto = require('crypto')
exports.idate = idate

exports.randomToken = (length = 32) => crypto.randomBytes(length / 2).toString('hex')

exports.md5 = (text, encode = 'hex') => {
  const hash = crypto.createHash('md5')

  hash.update(text)

  return hash.digest(encode)
}

exports.randomNumber = () => {
  return Math.floor(Math.random() * 10)
}

exports.pickBy = (obj, fn = v => typeof v !== 'undefined') => {
  const data = {}
  
  for (const key in obj) {
    if (fn(obj[key], key, obj)) {
      data[key] = obj[key]
    }
  }

  return data
}

exports.doPage = (ctx, maxLimit = 100) => {
  const page = Math.abs(ctx.query.page || 1)
  let limit = Math.min(Math.abs(ctx.query.pageSize || 10), maxLimit)

  return { offset: (page - 1) * limit, limit }
}

exports.getIp = (ctx) => {
  return ctx.headers['x-forwarded-for'] ||
    ctx.connection.remoteAddress ||
    ctx.socket.remoteAddress ||
    ctx.connection.socket.remoteAddress;
}

exports.isEmpty = function (o) {
  for (const k in o) {
    return false
  }

  return true
}
